package com.util;

import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

public class HttpClientUtil {
    public final static RequestConfig requestConfig;
    public final static PoolingHttpClientConnectionManager cm;
    static {
        requestConfig = RequestConfig
            .custom()
            .setConnectionRequestTimeout(40000)
            .setConnectTimeout(15000)
            .setSocketTimeout(15000).build();
        
        LayeredConnectionSocketFactory sslsf = null;
        try {
            sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        // 最大连接数
        cm.setMaxTotal(100);
        // 每个路由最大连接数
        cm.setDefaultMaxPerRoute(50);
    }

    public static CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = HttpClients
            .custom()
            .setConnectionManager(cm)
            //  设置重试次数，默认是3，当前是禁用
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .build();
        // 如果不采用连接池就是这种方式获取连接
        // CloseableHttpClient httpClient = HttpClients.createDefault();
        return httpClient;
    }
}
